<template>
  <div class="bg-bg_color" style="padding: 20px">
    <!-- 搜索框部分 -->
    <div>
      <el-form :inline="true" :model="findCondition" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="findCondition.userName" placeholder="请输入姓名" clearable>
            <template #suffix>
              <IconifyIconOnline icon="material-symbols:search" class="el-input__icon" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="findCondition.phoneNub" placeholder="请输入电话" clearable>
            <template #suffix>
              <IconifyIconOnline icon="material-symbols:phone-android-outline" class="el-input__icon" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="">
          <el-input v-model="findCondition.address" placeholder="请输入地址" clearable>
            <template #suffix>
              <IconifyIconOnline icon="material-symbols:edit-location-alt-outline" class="el-input__icon" />
            </template>
          </el-input>
        </el-form-item>

        <!-- 按键操作 -->
        <el-form-item>
          <el-button type="primary" @click="onSubmit"> <IconifyIconOnline icon="material-symbols:search" class="el-icon--left" />查询 </el-button>
          <el-button type="" @click="onReset"><IconifyIconOnline icon="material-symbols:wifi-protected-setup" class="el-icon--left" />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="flex justify-between" style="margin-bottom: 20px">
      <h3 />
      <el-button type="primary" @click="addFormVisible = true">
        <IconifyIconOnline icon="material-symbols:add-circle-outline" class="el-icon--left" />添加用户</el-button
      >
    </div>

    <!-- 表格部分 -->
    <div>
      <el-table :data="userList.list" stripe border>
        <el-table-column align="center" type="index" width="50" />
        <el-table-column align="center" prop="id" label="用户编号" width="100" />
        <el-table-column align="center" prop="userName" label="姓名" width="100" />
        <el-table-column align="center" prop="phoneNub" label="电话(账号)" width="120" />
        <el-table-column align="center" label="姓别" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.sex">男</el-tag>
            <el-tag v-else type="warning">女</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="角色" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.role == 'admin'">管理员</el-tag>
            <el-tag v-else type="success">普通用户</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="address" label="地址" min-width="200" />
        <el-table-column align="center" prop="createTime" label="注册时间" width="180" />
        <el-table-column align="center" fixed="right" prop="name" label="操作" width="220">
          <template #default="scope">
            <el-button size="small" type="success" @click="editUser(scope.row)"
              ><IconifyIconOnline icon="material-symbols:edit-square-outline" class="el-icon--left" />编辑</el-button
            >
            <el-button size="small" type="danger" @click="deleteUser(scope.row.id)"
              ><IconifyIconOnline icon="material-symbols:delete-forever-outline-rounded" class="el-icon--left" />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页部分 -->
    <div class="flex justify-end" style="margin-top: 20px">
      <el-pagination
        @current-change="handleCurrentChange"
        :page-size="pageSet.pageSize"
        v-model:current-page="pageSet.pageNub"
        layout="prev, pager, next"
        :total="userList.totle"
      />
    </div>

    <!-- 添加 -->
    <el-dialog v-model="addFormVisible" title="添加用户">
      <el-form ref="ruleFormRef" :rules="rules" status-icon label-position="right" label-width="100px" :model="addUser" style="max-width: 360px">
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="addUser.userName" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="addUser.sex" class="ml-4">
            <el-radio :label="true" size="large">男生</el-radio>
            <el-radio :label="false" size="large">女生</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="电话" prop="phoneNub">
          <el-input v-model="addUser.phoneNub" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUser.password" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="addUser.role">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="common" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm(ruleFormRef)"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog v-model="editFormVisible" title="编辑用户">
      <el-form ref="ruleFormRef" :rules="rules" status-icon label-position="right" label-width="100px" :model="addUser" style="max-width: 360px">
        <el-form-item label="姓名">
          <el-input v-model="updateUser.userName" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="updateUser.sex" class="ml-4">
            <el-radio :label="true" size="large">男生</el-radio>
            <el-radio :label="false" size="large">女生</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="updateUser.phoneNub" />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="updateUser.address" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="updateUser.role">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="common" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除用户 -->
    <el-dialog v-model="deleteDialogVisible" title="温馨提示" width="30%">
      <span>确定删除</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="deleteUserByIdApi"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { getUserList, register, updateUserById, deleteUserById } from "@/api/user";
import { message } from "@/utils/message";
import { ref, reactive, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";

defineOptions({
  name: "UserList"
});

const userList = reactive({
  totle: 0,
  list: []
});

onMounted(() => {
  console.log(`the component is now mounted.`);
  getUserListApi(null);
});

// 接口请求参数
const findCondition = reactive({
  phoneNub: "",
  userName: "",
  address: ""
});
const pageSet = reactive({
  pageNub: 1,
  pageSize: 8
});

async function getUserListApi(findCondition) {
  const result = await getUserList(pageSet.pageNub, pageSet.pageSize, findCondition);
  console.log("接口数据================", result);
  if (result.code == 200) {
    message("获取成功", { type: "success" });
    // 赋值
    userList.list = result.data.records;
    userList.totle = result.data.total;
  } else {
    message(result.message, { type: "error" });
  }
}

// 条件查询
function onSubmit() {
  getUserListApi(findCondition);
}
function onReset() {
  findCondition.address = "";
  findCondition.phoneNub = "";
  findCondition.userName = "";
}

// 分页
function handleCurrentChange(pageNub) {
  console.log(pageNub);
  getUserListApi(findCondition);
}

// ==========添加用户===========================
const addFormVisible = ref(false);

const addUser = reactive({
  userName: "",
  phoneNub: "",
  password: "",
  sex: true,
  address: "萍乡学院",
  role: "common"
});

const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  userName: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 5, message: "请输入正确名字", trigger: "blur" }
  ],
  phoneNub: [
    { required: true, message: "请输入电话", trigger: "blur" },
    { min: 11, max: 11, message: "请输入正确11位手机号", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 3, max: 11, message: "密码太简单了", trigger: "blur" }
  ]
});

const submitAddForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // 表单校验通过
      console.log("submit!", addUser);
      const result = await register(addUser);
      console.log(result);
      if (result.code == 200) {
        message("添加成功", { type: "success" });
        // 关弹窗 刷新数据
        getUserListApi(findCondition);
        addFormVisible.value = false;
      } else {
        message(result.message, { type: "error" });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
// ==========编辑用户===========================
const editFormVisible = ref(false);

const updateUser = reactive({
  id: 0,
  userName: "",
  phoneNub: "",
  sex: true,
  address: "萍乡学院",
  role: "common"
});

function editUser(row) {
  console.log("编辑", row);
  editFormVisible.value = true;

  updateUser.id = row.id;
  updateUser.userName = row.userName;
  updateUser.phoneNub = row.phoneNub;
  updateUser.sex = row.sex;
  updateUser.address = row.address;
  updateUser.role = row.role;
}

async function submitEditForm() {
  console.log("submit!", updateUser);
  const result = await updateUserById(updateUser);
  if (result.code == 200) {
    message("编辑成功", { type: "success" });
    // 关弹窗 刷新数据
    getUserListApi(findCondition);
    editFormVisible.value = false;
  } else {
    message(result.message, { type: "error" });
  }
}

// 删除用户
const deleteDialogVisible = ref(false);
const userId = ref();

function deleteUser(id: number) {
  console.log("删除", id);
  deleteDialogVisible.value = true;
  userId.value = id;
}

async function deleteUserByIdApi() {
  console.log("submit!", userId.value);
  const result = await deleteUserById(userId.value);
  if (result.code == 200) {
    message("删除成功", { type: "success" });
    // 关弹窗 刷新数据
    getUserListApi(findCondition);
    deleteDialogVisible.value = false;
  } else {
    message(result.message, { type: "error" });
  }
}
</script>
